package resource

import (
	"crypto/md5"
	"encoding/hex"
	"time"
)

func NewMeta() *Meta {
	t := time.Now().Unix()
	return &Meta{
		CreateAt: t,
	}
}
func (c *Meta) TableName() string {
	return "metas"
}
func NewSpec() *Spec {
	return &Spec{
		Extra: map[string]string{},
	}
}
func (c *Spec) TableName() string {
	return "specs"
}
func NewCost() *Cost {
	return &Cost{}
}
func (c *Cost) TableName() string {
	return "costs"
}
func NewStatus() *Status {
	return &Status{
		PublicAddress:  []string{},
		PrivateAddress: []string{},
	}
}
func (c *Status) TableName() string {
	return "status"
}
func NewResource() *Resource {
	return &Resource{
		Meta:        NewMeta(),
		Spec:        NewSpec(),
		Cost:        NewCost(),
		Status:      NewStatus(),
		Tags:        []*Tag{},
		ContentHash: &ContentHash{},
	}
}

func MakeHash(data string) (string, error) {
	h := md5.New()
	_, err := h.Write([]byte(data))
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(h.Sum(nil)), nil

}
func (r *Resource) MakeContentHash() error {
	if r.Spec != nil {
		ds, err := MakeHash(r.Spec.String())
		if err != nil {
			return err
		}
		r.ContentHash.SpecHash = ds
	}
	if r.Cost != nil {
		dc, err := MakeHash(r.Cost.String())
		if err != nil {
			return err
		}
		r.ContentHash.CostHash = dc
	}
	if r.Status != nil {
		dst, err := MakeHash(r.Status.String())
		if err != nil {
			return err
		}
		r.ContentHash.StatusHash = dst
	}
	if r.Status != nil {
		dst, err := MakeHash(r.Status.String())
		if err != nil {
			return err
		}
		r.ContentHash.StatusHash = dst
	}
	return nil
}

func NewSearchRequest() *SearchRequest {
	return &SearchRequest{
		Tag: map[string]string{},
	}
}

func NewDeleteRequest() *DeleteRequest {
	return &DeleteRequest{}
}
func NewTag() *Tag {
	return &Tag{
		Extra: map[string]string{},
	}
}

func NewKVTag(p TAG_PURPOSE, key, value string) *Tag {
	return &Tag{
		UpdateAt: time.Now().Unix(),
		Purpose:  p,
		Key:      key,
		Value:    value,
		Extra:    map[string]string{},
	}
}
func (r *Resource) AddTag(tag *Tag) {
	r.Tags = append(r.Tags, tag)
}

// gorm 保存时
func (c *Tag) TableName() string {
	return "tags"
}

func NewContentHash() *ContentHash {
	return &ContentHash{}
}

func NewResourceSet() *ResourceSet {
	return &ResourceSet{
		Items: []*Resource{},
	}
}

func (r *ResourceSet) AddItem(in *Resource) {
	r.Items = append(r.Items, in)
	r.Total = int64(len(r.Items))
}
